<template>
  <view class="search-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-container">
        <uni-icons type="arrowleft" size="22" color="#666" @click="goBack"></uni-icons>
        <view class="search-input">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <input 
            type="text" 
            v-model="searchText" 
            placeholder="请输入商品名称" 
            placeholder-class="placeholder"
            confirm-type="search"
            @confirm="doSearch"
            @input="onInput"
            focus
          />
          <uni-icons 
            v-if="searchText" 
            type="clear" 
            size="18" 
            color="#999" 
            @click="clearSearch"
          ></uni-icons>
        </view>
        <text class="cancel-btn" @click="goBack" v-if="!searchText">取消</text>
        <text class="search-btn" @click="doSearch" v-else>搜索</text>
      </view>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="showHistory">
      <view class="section-header">
        <text class="title">搜索历史</text>
        <uni-icons type="trash" size="18" color="#999" @click="clearHistory"></uni-icons>
      </view>
      <view class="history-list">
        <view 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @click="searchFromHistory(item)"
        >
          <text>{{ item }}</text>
        </view>
      </view>
    </view>
    
    <!-- 热门搜索 -->
    <view class="hot-search" v-if="showHistory">
      <view class="section-header">
        <text class="title">热门搜索</text>
      </view>
      <view class="hot-list">
        <view 
          class="hot-item" 
          v-for="(item, index) in hotSearchList" 
          :key="index"
          @click="searchFromHot(item)"
        >
          <text>{{ item }}</text>
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <scroll-view 
      class="search-result" 
      scroll-y 
      v-if="showResult"
      @scrolltolower="loadMore"
    >
      <!-- 筛选栏 -->
      <view class="filter-bar">
        <view 
          class="filter-item" 
          :class="{active: sortType === 'default'}"
          @click="changeSort('default')"
        >
          <text>综合</text>
        </view>
        <view 
          class="filter-item" 
          :class="{active: sortType === 'sales'}"
          @click="changeSort('sales')"
        >
          <text>销量</text>
          <uni-icons 
            :type="salesSortOrder === 'asc' ? 'arrowup' : 'arrowdown'" 
            size="14" 
            color="#666"
            v-if="sortType === 'sales'"
          ></uni-icons>
        </view>
        <view 
          class="filter-item" 
          :class="{active: sortType === 'price'}"
          @click="changeSort('price')"
        >
          <text>价格</text>
          <uni-icons 
            :type="priceSortOrder === 'asc' ? 'arrowup' : 'arrowdown'" 
            size="14" 
            color="#666"
            v-if="sortType === 'price'"
          ></uni-icons>
        </view>
        <view 
          class="filter-item" 
          :class="{active: sortType === 'rating'}"
          @click="changeSort('rating')"
        >
          <text>评价</text>
        </view>
      </view>
      
      <!-- 商品列表 -->
      <view class="product-list">
        <product-card 
          v-for="product in searchResult" 
          :key="product.id"
          :product="product"
          @click="viewProduct(product.id)"
        />
      </view>
      
      <!-- 加载状态 -->
      <view class="load-status">
        <uni-load-more 
          :status="loadStatus" 
          :content-text="{
            contentdown: '上拉加载更多',
            contentrefresh: '加载中',
            contentnomore: '没有更多了'
          }" 
        />
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="searchResult.length === 0 && !loading">
        <image 
          class="empty-image" 
          src="/static/images/empty-search.png" 
          mode="aspectFit"
        ></image>
        <text class="empty-text">没有找到相关商品</text>
        <text class="empty-tip">换个关键词试试吧</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import ProductCard from './components/ProductCard.vue'

// 搜索相关
const searchText = ref('')
const showHistory = ref(true)
const showResult = ref(false)
const searchHistory = ref([])
const hotSearchList = ref(['手机', '笔记本电脑', '耳机', '智能手表', '运动鞋', 'T恤', '牛奶', '零食'])

// 搜索结果
const searchResult = ref([])
const page = ref(1)
const pageSize = 10
const loadStatus = ref('more') // more / loading / noMore
const loading = ref(false)

// 排序相关
const sortType = ref('default') // default / sales / price / rating
const priceSortOrder = ref('asc') // asc / desc
const salesSortOrder = ref('desc') // asc / desc

// 页面加载
onLoad(() => {
  // 从本地存储加载搜索历史
  loadSearchHistory()
})

// 加载搜索历史
const loadSearchHistory = () => {
  const history = uni.getStorageSync('searchHistory') || []
  searchHistory.value = history.slice(0, 10) // 最多显示10条
}

// 保存搜索历史
const saveSearchHistory = (keyword) => {
  if (!keyword) return
  
  // 去重
  const index = searchHistory.value.indexOf(keyword)
  if (index !== -1) {
    searchHistory.value.splice(index, 1)
  }
  
  // 添加到开头
  searchHistory.value.unshift(keyword)
  
  // 限制数量
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
  
  // 保存到本地
  uni.setStorageSync('searchHistory', searchHistory.value)
}

// 清空搜索历史
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        searchHistory.value = []
        uni.setStorageSync('searchHistory', [])
      }
    }
  })
}

// 执行搜索
const doSearch = () => {
  if (!searchText.value.trim()) {
    uni.showToast({
      title: '请输入搜索内容',
      icon: 'none'
    })
    return
  }
  
  // 保存搜索历史
  saveSearchHistory(searchText.value.trim())
  
  // 显示搜索结果
  showHistory.value = false
  showResult.value = true
  
  // 重置搜索条件
  page.value = 1
  searchResult.value = []
  loadStatus.value = 'more'
  
  // 执行搜索
  fetchSearchResult()
}

// 从历史记录搜索
const searchFromHistory = (keyword) => {
  searchText.value = keyword
  doSearch()
}

// 从热门搜索
const searchFromHot = (keyword) => {
  searchText.value = keyword
  doSearch()
}

// 清空搜索
const clearSearch = () => {
  searchText.value = ''
}

// 输入变化
const onInput = () => {
  if (!searchText.value) {
    showHistory.value = true
    showResult.value = false
  }
}

// 获取搜索结果
const fetchSearchResult = () => {
  if (loadStatus.value === 'noMore') return
  
  loadStatus.value = 'loading'
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    const newData = generateMockProducts(
      page.value, 
      pageSize, 
      searchText.value,
      sortType.value,
      sortType.value === 'price' ? priceSortOrder.value : 
      sortType.value === 'sales' ? salesSortOrder.value : 'desc'
    )
    
    if (newData.length === 0) {
      loadStatus.value = 'noMore'
      if (page.value === 1) {
        searchResult.value = []
      }
    } else {
      searchResult.value = page.value === 1 ? newData : [...searchResult.value, ...newData]
      page.value++
      loadStatus.value = newData.length < pageSize ? 'noMore' : 'more'
    }
    
    loading.value = false
  }, 800)
}

// 生成模拟商品数据
const generateMockProducts = (page, size, keyword, sortType, sortOrder) => {
  if (page > 3) return [] // 模拟只有3页数据
  
  const baseData = [
    {
      id: '1',
      name: `${keyword}商品1`,
      price: (100 + Math.random() * 900).toFixed(2),
      originalPrice: (100 + Math.random() * 1000).toFixed(2),
      image: '/static/product.jpg',
      sales: Math.floor(Math.random() * 1000),
      rating: (4 + Math.random()).toFixed(1)
    },
    {
      id: '2',
      name: `${keyword}商品2`,
      price: (100 + Math.random() * 900).toFixed(2),
      originalPrice: (100 + Math.random() * 1000).toFixed(2),
      image: '/static/product2.jpg',
      sales: Math.floor(Math.random() * 1000),
      rating: (4 + Math.random()).toFixed(1)
    },
    {
      id: '3',
      name: `${keyword}商品3`,
      price: (100 + Math.random() * 900).toFixed(2),
      originalPrice: (100 + Math.random() * 1000).toFixed(2),
      image: '/static/product.jpg',
      sales: Math.floor(Math.random() * 1000),
      rating: (4 + Math.random()).toFixed(1)
    }
  ]
  
  // 模拟排序
  if (sortType === 'price') {
    baseData.sort((a, b) => {
      return sortOrder === 'asc' 
        ? parseFloat(a.price) - parseFloat(b.price)
        : parseFloat(b.price) - parseFloat(a.price)
    })
  } else if (sortType === 'sales') {
    baseData.sort((a, b) => {
      return sortOrder === 'asc' 
        ? a.sales - b.sales
        : b.sales - a.sales
    })
  } else if (sortType === 'rating') {
    baseData.sort((a, b) => parseFloat(b.rating) - parseFloat(a.rating))
  }
  
  // 模拟分页
  return baseData.slice(0, size)
}

// 改变排序方式
const changeSort = (type) => {
  if (type === sortType.value) {
    // 相同排序类型，切换排序顺序
    if (type === 'price') {
      priceSortOrder.value = priceSortOrder.value === 'asc' ? 'desc' : 'asc'
    } else if (type === 'sales') {
      salesSortOrder.value = salesSortOrder.value === 'asc' ? 'desc' : 'asc'
    }
  } else {
    // 不同排序类型，重置为默认顺序
    sortType.value = type
    if (type === 'price') {
      priceSortOrder.value = 'asc'
    } else if (type === 'sales') {
      salesSortOrder.value = 'desc'
    }
  }
  
  // 重新加载数据
  page.value = 1
  searchResult.value = []
  loadStatus.value = 'more'
  fetchSearchResult()
}

// 加载更多
const loadMore = () => {
  fetchSearchResult()
}

// 查看商品详情
const viewProduct = (id) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${id}`
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>

.search-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $white-bg;
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: $white-bg;
  border-bottom: 1rpx solid #f5f5f5;
  
  .search-input-container {
    display: flex;
    align-items: center;
    
    .search-input {
      flex: 1;
      display: flex;
      align-items: center;
      height: 70rpx;
      background-color: $light-bg;
      border-radius: 35rpx;
      padding: 0 25rpx;
      margin: 0 20rpx;
      
      input {
        flex: 1;
        font-size: $font-size-28rpx;
        color: $text-color;
        margin-left: 15rpx;
      }
    }
    
    .cancel-btn, .search-btn {
      font-size: $font-size-28rpx;
      color: $text-color;
    }
    
    .search-btn {
      color: $primary-color;
    }
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .title {
    font-size: $font-size-28rpx;
    font-weight: bold;
    color: $text-color;
  }
}

.search-history, .hot-search {
  padding: 30rpx;
  
  .history-list, .hot-list {
    display: flex;
    flex-wrap: wrap;
    
    .history-item, .hot-item {
      padding: 12rpx 25rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      font-size: $font-size-26rpx;
      color: $text-color;
      background-color: $light-bg;
      border-radius: 30rpx;
    }
    
    .hot-item {
      background-color: rgba(255, 140, 0, 0.1);
      color: $primary-color;
    }
  }
}

.search-result {
  flex: 1;
  height: calc(100vh - 110rpx);
}

.filter-bar {
  display: flex;
  background-color: $white-bg;
  border-bottom: 1rpx solid #f5f5f5;
  
  .filter-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 25rpx 0;
    font-size: $font-size-28rpx;
    color: $text-color;
    
    &.active {
      color: $primary-color;
    }
  }
}

.product-list {
  padding: 20rpx;
}

.load-status {
  padding: 30rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: $font-size-30rpx;
    color: $text-color;
    margin-bottom: 15rpx;
  }
  
  .empty-tip {
    font-size: $font-size-26rpx;
    color: $text-color-666;
  }
}

.placeholder {
  color: #999;
  font-size: $font-size-28rpx;
}
</style>